package com.simple.datax.flow.processor;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.flow.constants.ProcessResultConstants;
import com.simple.datax.flow.constants.TaskActivityConstants;
import com.simple.datax.flow.dao.ibatis.model.FlowActivityInstance;
import com.simple.datax.flow.message.BaseEcMessage;
import com.simple.datax.flow.message.EcFlowRespMessage;
import com.simple.datax.flow.message.EcFlowRespMessageBody.ResponseActionResult;
import com.simple.datax.flow.preprocessor.PreProcessorService;

/** 
 * @Title: EcFlow201RespMessageProcess.java 
 * @Package com.simple.datax.flow.processor 
 * @Description: TODO(添EcFlow201RespMessageProcess报文处理) 
 * @author tonney 
 * @date 2013-3-4 下午06:49:30 
 * @version V1.0 
 */
public class EcFlow201RespMessageProcessor extends BaseMessageProcessor implements MessageProcessIF{
	public Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public int process(BaseEcMessage message) {
		List<BaseEcMessage> messageList = null;
		PreProcessorService preProcessor = null;
		int result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
		EcFlowRespMessage ecFlowRespMessage = null;
		String xml = "";
		try {
			ecFlowRespMessage = (EcFlowRespMessage)message;
			List<String> xmlMessageList = new ArrayList<String>();
			List<FlowActivityInstance> activityInstanceList = new ArrayList<FlowActivityInstance>();
			/***************************** 协议企业接收后预处理 BEGIN ****************************************/
			messageList = new ArrayList<BaseEcMessage>();
			preProcessor = preProcessorAdaptor
					.getPreProcessorServiceByEcode(ecFlowRespMessage
							.getFlowRespMessageHead().getSenderId());
			if (preProcessor != null) {
				result = preProcessor.recvPreProcessor(ecFlowRespMessage,
						messageList); // 预处理报文
			} else {
				log.warn("Tcs Response Message No Preprocessor,sendid["+ecFlowRespMessage
						.getFlowRespMessageHead().getSenderId()+"]");
			}
			/***************************** 协议企业接收后预处理 END ********************************************/

			if (result == ProcessResultConstants.STATUS_SUCCESS) {
				result = processActivitys(messageList, xmlMessageList, activityInstanceList);
				if(result == ProcessResultConstants.STATUS_SUCCESS){
					result = updateFlowActivitys(activityInstanceList);
					if(result == ProcessResultConstants.STATUS_SUCCESS){
						result = sendXmlMessages(xmlMessageList);
//						if(result != ProcessResultConstants.STATUS_SUCCESS){
//							log.error("EcFlow201RespMessageProcessor::process fail!");
//						}
					}
				}
			}else{
				log.warn("Tcs Response Message Preprocessor failure,failcode="+ProcessResultConstants.getProcDetail(result)+"]");
			}
		} catch (Exception e) {
			// 如果执行到此步,说明有异常,则返回错误报文给发送者
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("EcFlow201RespMessageProcessor::process error==>" + e.toString());
		} finally {
			// 并且原始报文解析成功，但是报文处理过程中异常，则发送错误响应报文
			if (result != ProcessResultConstants.STATUS_SUCCESS) {
				log.error("EcFlow201RespMessageProcessor::process fail,taskid["+ecFlowRespMessage.getFlowRespMessageBody().getEcFlowResponseHead().getTaskId()+"]");
			}
		}
		return result;
	}
	
	/**
	 * 处理本次活动预处理后生成的活动集，如果活动集中有一个失败则本次任务中对应的活动失败
	 * @param messageList  预处理后生成的活动集
	 * @param xmlMessageList  活动集处理后的XML报文字符串
	 * @param activityInstanceList  活动集信息，用于保存至数据库和缓存
	 * @return
	 */
	public int processActivitys(List<BaseEcMessage> messageList,List<String> xmlMessageList,List<FlowActivityInstance> activityInstanceList){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		String flowid = null;
		String taskid = null;
		List<ResponseActionResult> activityNoList = null;
		String activityNo = null;
		FlowActivityInstance activityInstance = null;
//		PreProcessorService preProcessor = null;
		String xmlMessage = null;
		try{
			if (messageList != null && messageList.size() > 0) {
				EcFlowRespMessage ecRespMessage = null;
				for (BaseEcMessage baseMessage : messageList) {
					try{
						ecRespMessage = (EcFlowRespMessage)baseMessage;
						flowid = ecRespMessage.getFlowRespMessageBody().getEcFlowResponseHead().getBpNo();
						taskid = ecRespMessage.getFlowRespMessageBody().getEcFlowResponseHead().getTaskId();
						activityNoList = ecRespMessage.getFlowRespMessageBody().getActionResultList();
						if (activityNoList != null	&& activityNoList.size() >= 1) {
							for(ResponseActionResult actionResult:activityNoList){
								activityNo = actionResult.getActionId();
									activityInstance = taskActivityManager
											.getFlowActivityInstance(flowid,
													activityNo);
									if (activityInstance != null) {
										if (result == ProcessResultConstants.STATUS_SUCCESS) {
											result = taskActivityManager
													.editMessageByFlowidAndActivityNo(
															flowid, activityNo,
															ecRespMessage,
															activityInstance);
											if (result == ProcessResultConstants.STATUS_SUCCESS) {
	//											/***************************** 协议企业发送前预处理 BEGIN ******************************************/
	//											preProcessor = preProcessorAdaptor
	//													.getPreProcessorServiceByEcode(ecRespMessage.getFlowRespMessageHead().getReceiverId());
	//											if (preProcessor != null) {
	//												result = preProcessor
	//														.sendPreProcessor(ecRespMessage);
	//											}
	//											/***************************** 协议企业发送前预处理 BEGIN ******************************************/
		
	//											if (result == ProcessResultConstants.STATUS_SUCCESS) {
	//												try {
													xmlMessage = messageConvertor
													.convert2StringXml(ecRespMessage);
													xmlMessageList.add(xmlMessage);
													// 记录任务处理结果到数据库，同时修改redis缓存记录
													// taskMessageManager.saveTaskMessage(activityInstance,ecMessage);//保存报文发送记录
													activityInstance
															.setTaskId(taskid);
													activityInstance
															.setStatus(TaskActivityConstants.STATUS_SUCCESS);
													activityInstance
															.setDueResult("1");
													activityInstance
															.setMessageId(ecRespMessage.getFlowRespMessageHead().getMessageId());
													activityInstanceList.add(activityInstance);
	//											} else { // 任务处理失败，修改任务状态
	//												log.warn("BaseMessageProcessor::processActivitys warn=>PreProcessor before Send failure");
	//												break;
	//											}
											} else {
												log.warn("BaseMessageProcessor::processActivitys warn=> Edit EcMessage failure");
												break;
											}
										}
									} else {
										result = ProcessResultConstants.STATUS_ACTIVITY_INVALID;
										log.warn("BaseMessageProcessor::processActivitys warn=> getFlowActivityInstance return null");
										break;
									}
							}
						} else {
							result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
							log.error("BaseMessageProcessor::processActivitys warn=> No ActivityNo");
							break;
						}
					}catch(Exception e){
						result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
						log.error("BaseMessageProcessor::processActivitys Process Message Error=>"+e.toString());		
						break;
					}
				}
			} else {
				result = ProcessResultConstants.STATUS_RECV_PROCESS_EXCEPTION;
				log.error("BaseMessageProcessor::processActivitys warn=> Message PreProcess return null");
			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::processActivity Error=>"+e.toString());		
		}
		return result;
	}
	
}
